package com.dream.technology.components.riskControl.imp;

import com.dream.technology.components.riskControl.SymbolAnalysis;
import com.dream.technology.db.entity.RcOperationalSymbol;
import com.dream.technology.service.RcCustomerTagService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author chen_q_i@163.com
 * 2018/12/6 : 16:17.
 * @version : 1.0
 */
@Component("symbolAnalysisImp")
public class SymbolAnalysisImp implements SymbolAnalysis {

    private static final Logger logger = LoggerFactory.getLogger(RcCustomerTagService.class);

    @Autowired(required=false)
    private Map<String, RcOperationalSymbol> symbolMap;

    /**
     * 回显描述规则 用于风控验证
     *
     * @param name       字段名称
     * @param symbolCode 符号代码 EQ NEQ ....
     * @param value      比较值
     * @return
     */
    @Override
    public String analysisSymbolName(String name, String symbolCode, String value) {

        if (!symbolCode.contains(",")) {
            RcOperationalSymbol rcOperationalSymbol = symbolMap.get(symbolCode);
            return name + rcOperationalSymbol.getName() + value;
        } else {
            return analysisSymbolNameScope(name, symbolCode, value);
        }

    }



    /**
     * 解析范围描述
     *
     * @param name
     * @param symbolCode
     * @param value
     * @return
     */
	public String analysisSymbolNameScope(String name, String symbolCode, String value) {
		String[] sys = symbolCode.split(",");
		String[] split = value.split(",");
		if (sys.length < 2) {
			return analysisSymbolName(name, sys[0], split[0]);
		}

		String min = split[0];
		String max = split[1];
		String minSys = sys[0];
		String maxSys = sys[1];
		String descript = "";
		if (!"undefined".equals(min)) {
			descript += analysisSymbolName(name, minSys, min);
		}
		if (!"undefined".equals(max)) {
			if (StringUtils.isNoneEmpty(descript)) {
				descript += "且";
			}
			descript += analysisSymbolName(name, maxSys, max);
		}
		return descript;
	}



    /**
     * 规则表达式替换掉符号转制符串数组
     * "ale|cd&(jke|iuy)   [ale, cd, jke, iuy]
     *
     * @param expression
     * @return
     */
    @Override
    public String[] repleaseSymbolCodes(String expression) {
        logger.info("expression======{}",expression);
        String s = expression.replaceAll("&|\\||\\(|\\)", ",");
        logger.info("s================>{}"+s);
        String[] split = s.replaceAll(",+",",").split(",");
       logger.info(split.length + "==="+ Arrays.toString(split));
        return  split;
    }


    /**
     * 获取字符串表达式
     *
     * @param collectionRule 规则集表达式
     * @param rulesAnalsMap  k 规则别名 v 规则对应的文字表达
     * @return
     */
    @Override
    public  String getExp(String collectionRule,Map<String,String> rulesAnalsMap){

        String[] strings = repleaseSymbolCodes(collectionRule);
        // 大坑 需要先替换长的，后替换短的
        List<String> collect = Arrays.stream(strings).filter(str -> !str.isEmpty()).collect(Collectors.toList());
        collect.sort((x, y) -> {
            if (x.length() > y.length()) {
                return -1;
            }
            return 1;
        });
        for (String rule : collect) {
            String s   = rulesAnalsMap.get(rule);
            if (StringUtils.isEmpty(s)){
                logger.error("{} is null ",rule);
                return rule + "规则表达式无相应规则，请检查后重试";
            }else {
                collectionRule = collectionRule.replaceAll(rule,s);
            }
        }
        collectionRule =    collectionRule.replaceAll("\\|", " 或 ");
        collectionRule =   collectionRule.replaceAll("&"," 且 ");
        return collectionRule;
    }

}
